<template>
  <div style="height: 560px; overflow-y: auto">
    <el-tabs type="border-card" style="height: 540px">
      <el-tab-pane label="溯源详情">
        <div class="common-layout">
          <el-container>
            <el-aside width="400px">
              <img
                :src="proddata.showUrl"
                alt=""
                style="border-radius: 24px; margin-left: 40px"
                width="300px"
                height="300px"
            /></el-aside>
            <el-main>
              <el-form
                :inline="true"
                label-width="140"
                class="demo-form-inline"
                style="margin-right: 100px"
              >
                <h1 style="font-size: 36px; margin-left: 40px">
                  {{ proddata.productName }}
                </h1>

                <el-form-item style="width: 400px">
                  <span style="margin-left: 40px"
                    >生产批次：{{ proddata.productionBatch }}</span
                  >
                </el-form-item>
                <el-form-item style="width: 400px">
                  <span style="margin-left: 40px"
                    >保质期 (天):{{ proddata.shelfLife }}</span
                  >
                </el-form-item>
                <br />
                <el-form-item style="width: 400px">
                  <span style="margin-left: 40px"
                    >生产许可证号：{{ proddata.licenseNumber }}</span
                  >
                </el-form-item>
                <el-form-item style="width: 400px">
                  <span style="margin-left: 40px"
                    >生产企业：{{ proddata.enterprise }}</span
                  >
                </el-form-item>
              </el-form>
              <br />
              <span style="margin-left: 40px; font-size: 20px"
                >产品检验报告</span
              >
              <br />
              <br />
              <el-upload
                style="margin-left: 40px"
                v-model:file-list="fileList"
                :action="uploadAction"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :data="uploadData"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>

              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </el-main>
          </el-container>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-tabs type="border-card" style="margin-top: 20px; height: 1450px">
      <el-tab-pane label="养殖信息">
        <!-- 养殖信息 -->
        <el-form
          :inline="true"
          label-width="140"
          class="demo-form-inline"
          style="margin-right: 100px"
        >
          <span style="font-size: 22px; margin-left: 40px; color: #1e90ff">{{
            "养殖信息"
          }}</span>
          <el-button
            style="margin-left: 40px; width: 100px"
            type="primary"
            color="#DCDCDC"
            @click="openAdd"
            >设置</el-button
          >
          <el-divider />

          <el-form-item style="width: 400px">
            <span style="margin-left: 40px"
              >品种：{{ Addbreedbata.variety }}</span
            >
          </el-form-item>
          <el-form-item style="width: 400px">
            <span style="margin-left: 40px"
              >来源：{{ Addbreedbata.source }}</span
            >
          </el-form-item>
          <br />
          <el-form-item style="width: 400px">
            <span style="margin-left: 40px"
              >饲养天数：{{ Addbreedbata.feedingDays }}</span
            >
          </el-form-item>
          <el-form-item style="width: 400px">
            <span style="margin-left: 40px"
              >饲料品牌：{{ Addbreedbata.feedingBrand }}</span
            >
          </el-form-item>
          <br />
          <el-form-item style="width: 400px">
            <span style="margin-left: 40px"
              >饲养负责人：{{ Addbreedbata.feedingName }}</span
            >
          </el-form-item>
          <el-form-item style="width: 400px">
            <span style="margin-left: 40px"
              >出栏日期：{{ Addbreedbata.saleDate.substring(0, 10) }}</span
            >
          </el-form-item>
        </el-form>
        <!-- 添加修改框 -->
        <el-dialog
          title="养殖信息"
          v-model="from1.dialogFormVisible"
          width="500"
        >
          <el-form :model="form" :label-width="140">
            <el-form-item label="品种">
              <el-input v-model="Addbreedbata.variety" />
            </el-form-item>
            <el-form-item label="来源">
              <el-input v-model="Addbreedbata.source" />
            </el-form-item>
            <el-form-item label="饲养天数">
              <el-input v-model="Addbreedbata.feedingDays" />
            </el-form-item>
            <el-form-item label="饲料品牌">
              <el-input v-model="Addbreedbata.feedingBrand" />
            </el-form-item>
            <el-form-item label="饲养负责人">
              <el-input v-model="Addbreedbata.feedingName" />
            </el-form-item>
            <el-form-item label="出栏日期">
              <el-date-picker
                v-model="Addbreedbata.saleDate"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="Addbreed(from1.AddModify)" type="primary"
                >保存</el-button
              >
            </div>
          </template>
        </el-dialog>

        <!-- 保健信息 -->
        <el-form
          :inline="true"
          label-width="140"
          class="demo-form-inline"
          style="margin-right: 100px; margin-top: 40px"
        >
          <span style="font-size: 22px; margin-left: 40px; color: #1e90ff">{{
            "保健信息"
          }}</span>
          <!-- 新增行按钮 -->
          <el-button
            style="margin-left: 40px; width: 100px"
            type="primary"
            color="#DCDCDC"
            @click="addRow"
          >
            新增行
          </el-button>
          <el-divider />

          <el-divider />

          <!-- 表格 -->
          <el-table
            :data="tableData"
            border
            style="
              width: 100%;
              height: 230px;
              margin-bottom: 40px;
              margin-left: 40px;
            "
          >
            <!-- 饲养天数 -->
            <el-table-column prop="FeedingDays" label="饲养天数">
              <template #default="scope">
                <el-input
                  v-if="scope.row.ImmunityId == 0 || scope.row.UpdateImmunity1"
                  v-model="scope.row.FeedingDays"
                />
                <samp v-else>{{ scope.row.FeedingDays }}</samp>
              </template>
            </el-table-column>

            <!-- 保健方式 -->
            <el-table-column prop="ImmunityType" label="保健方式">
              <template #default="scope">
                <el-input
                  v-if="scope.row.ImmunityId == 0 || scope.row.UpdateImmunity1"
                  v-model="scope.row.ImmunityType"
                />
                <samp v-else>{{ scope.row.ImmunityType }}</samp>
              </template>
            </el-table-column>

            <!-- 保健方法 -->
            <el-table-column prop="ImmunityMethod" label="保健方法">
              <template #default="scope">
                <el-input
                  v-if="scope.row.ImmunityId == 0 || scope.row.UpdateImmunity1"
                  v-model="scope.row.ImmunityMethod"
                />

                <samp v-else>{{ scope.row.ImmunityMethod }}</samp>
              </template>
            </el-table-column>

            <!-- 操作列 -->
            <el-table-column label="操作">
              <template #default="{ $index, row }">
                <el-button
                  v-if="row.ImmunityId != 0 && !row.UpdateImmunity2"
                  link
                  @click="UpdateImmunity1($index)"
                  >修改</el-button
                >
                <el-button
                  v-else-if="row.UpdateImmunity"
                  @click="UpdateImmunity2(row)"
                  link
                >
                  修改
                </el-button>

                <el-button v-else link @click="AddImmunity($index)"
                  >保存</el-button
                >
                <el-button v-if="row.ImmunityMethod != ''" link>删除</el-button>

                <el-button v-else link @click="deleteRow($index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <span style="font-size: 22px; margin-left: 40px; color: #1e90ff">{{
            "动检证"
          }}</span>

          <el-divider />

          <el-upload
            style="margin-left: 40px"
            v-model:file-list="fileList"
            :action="uploadAction"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :data="uploadData"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form>
        <!-- 养殖企业信息 -->
        <el-form
          :inline="true"
          label-width="140"
          class="demo-form-inline"
          style="margin-right: 100px; margin-top: 40px"
        >
          <span style="font-size: 22px; margin-left: 40px; color: #1e90ff">{{
            "企业信息"
          }}</span>
          <el-button
            style="margin-left: 40px; width: 100px"
            type="primary"
            color="#DCDCDC"
            >设置</el-button
          >
          <el-divider />
          <el-form-item style="width: 400px">
            <span style="margin-left: 40px">养殖场：{{ proddata.farm }}</span>
          </el-form-item>
          <el-form-item style="width: 400px">
            <span style="margin-left: 40px"
              >负责人：{{ proddata.manager }}</span
            >
          </el-form-item>
          <br />
          <el-form-item style="width: 400px">
            <span style="margin-left: 40px"
              >存栏数量：{{ proddata.livestockQuantity }}</span
            >
          </el-form-item>
          <br />
          <br />
          <span
            style="
              font-size: 22px;
              margin-left: 40px;
              color: #1e90ff;
              margin-top: 40px;">
            {{ "企业照片" }}
          </span>

          <el-divider />

          <el-upload
            style="margin-left: 40px"
            v-model:file-list="fileList"
            :action="uploadAction"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :data="uploadData"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="屠宰信息">屠宰管理</el-tab-pane>
      <el-tab-pane label="深加工信息">深加工管理</el-tab-pane>
    </el-tabs>
  </div>
</template>


<script lang="ts" setup>
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { reactive, ref, onMounted, computed } from "vue";
import { Plus } from "@element-plus/icons-vue";

import type { UploadProps, UploadUserFile } from "element-plus";

import axios from "axios";
import { useCounterStore } from "@/stores/counter";
const router = useRouter();
const route = useRoute();
const store = useCounterStore();
onMounted(() => {
  // 获取产品数据
  fetchProductData();
  // 获取产品图片
  Obtainproductimg();
});
//#region 产品数据
interface ProductData {
  productId: string;
  productName: string;
  productionBatch: string;
  shelfLife: string;
  licenseNumber: string;
  enterprise: string;
  showUrl: string;
  variety: string;
  source: string;
  feedingDays: string;
  feedBrand: string;
  feedingPersonInCharge: string;
  outDate: string;
  farm: string;
  manager: string;
  livestockQuantity: string;
}

const proddata = reactive<ProductData>({
  productId: "",
  productName: "",
  productionBatch: "",
  shelfLife: "",
  licenseNumber: "",
  enterprise: "",
  showUrl: "",
  variety: "",
  source: "",
  feedingDays: "",
  feedBrand: "",
  feedingPersonInCharge: "",
  outDate: "",
  farm: "",
  manager: "",
  livestockQuantity: "",
});

//获取产品图片
const Obtainproductimg = async () => {
  try {
    const response = await axios({
      method: "get",
      url: "https://localhost:44352/api/User/UpLoad",
      params: {
        theRestId: route.query.productId,
      },
    });
    fileList.value = response.data.data;
  } catch (error) {
    ElMessage.error("获取产品数据失败");
  }
};
// 获取产品数据
const fetchProductData = async () => {
  try {
    const response = await axios({
      method: "get",
      url: "",
      params: {
        productId: route.query.productId,
      },
    });
    Object.assign(proddata, response.data.data);
    uploadData.value.theRestId = proddata.productId;
  } catch (error) {
    ElMessage.error("获取产品数据失败");
  }
};

const form = reactive({
  accountName: "",
  accountPass: "",
  validateCode: "",
  vCode: "",
  token: "",
});
const uploadData = ref({
  theRestId: "",
});
const uploadAction = computed(() => {
  // return `http://localhost:33777/api/Rabbit/UpLoad?theRestId=${proddata.productId}`;
});

const fileList = ref<UploadUserFile[]>([]);

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

// 删除产品图片
const handleRemove: UploadProps["onRemove"] = (uploadFile: any) => {
  axios({
    method: "delete",
    url: "https://localhost:44352/api/Img/ImgDel",
    params: {
      id: uploadFile.id,
    },
  }).then((res) => {
    console.log(uploadFile.Id);
    if (res.data.code == 500) {
      ElMessage.success(res.data.message);
      Obtainproductimg(); //重新获取图片
    } else {
      // 处理其他错误码
      ElMessage.error(res.data.message);
    }
  });
};
//预览产品图片
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  if (uploadFile.url) {
    dialogImageUrl.value = uploadFile.url;
    dialogVisible.value = true;
  } else {
    ElMessage.error("预览图片失败");
  }
};
//#endregion

//#region 养殖信息

//#region 免疫
// 定义表格行的类型
interface TableRow {
  ImmunityId: number;
  FeedingDays: number | null;
  ImmunityType: string;
  ImmunityMethod: string;
  UpdateImmunity1: boolean;
  UpdateImmunity2: boolean;
}

// 初始化表格数据，并指定类型
const tableData = ref<TableRow[]>([]);

// 新增行
const addRow = () => {
  tableData.value.push({
    ImmunityId: 0,
    FeedingDays: 0||null,
    ImmunityType: "",
    ImmunityMethod: "",
    UpdateImmunity1: false,
    UpdateImmunity2: false,
  });
};
//删除行
const deleteRow = (index: number) => {
  tableData.value.splice(index, 1);
};

// 新增行
const AddImmunity = (id: number) => {
  const data = {
    breedId: Addbreedbata.value.breedId, //品种id
    feedingDays: tableData.value[id].FeedingDays||null, //饲养天数
    immunityType: tableData.value[id].ImmunityType, //免疫类型
    immunityMethod: tableData.value[id].ImmunityMethod, //免疫方法
    creator: store.curr.userName //创建人
  };

  axios({
    method: "post",
    url: "https://localhost:44352/api/Immune/AddImmune",
    data: data,
  }).then((res) => {
    if (res.data.code == 300) {
      ElMessage.success(res.data.message);
      QueryImmunity();
    } else {
      ElMessage.error(res.data.message);
    }
  });
};

// 查询免疫
const QueryImmunity = () => {
  tableData.value = [];
  axios({
    method: "get",
    url: "https://localhost:44352/api/Immune/QueryImmune",
    data: { breedId: Addbreedbata.value.breedId },
  })
    .then((res) => {
      // console.log(res.data);
      for (let i = 0; i < res.data.data.length; i++) {
        tableData.value.push({
          ImmunityId: res.data.data[i].immunityId,
          FeedingDays: res.data.data[i].feedingDays,
          ImmunityType: res.data.data[i].immunityType,
          ImmunityMethod: res.data.data[i].immunityMethod,
          UpdateImmunity1: false,
          UpdateImmunity2: false,
        });
      }
    })
    .catch((error) => {
      console.error("查询免疫信息时出错:", error);
      ElMessage.error("查询免疫信息时出错，请稍后重试");
    });
};

// 修改免疫1
const UpdateImmunity1 = (id: number) => {
  // console.log(id);
  tableData.value[id].UpdateImmunity1 = true;
  tableData.value[id].UpdateImmunity2 = false;
};

// 修改免疫2
const UpdateImmunity2 = (data: any) => {
  // console.log(data);
};
//#endregion

const from1 = reactive({
  dialogFormVisible: false,
  AddModify: false,
  UpdateImmunity: false,
});

//打开新增框
const openAdd = () => {
  from1.dialogFormVisible = true;
};

const Addbreedbata = ref({
  productId: route.query.productId,
  breedId: 0,
  variety: "",
  source: "",
  feedingDays: null,
  feedingBrand: "",
  feedingName: "",
  saleDate: "",
  farmEnterpriseId: 0,
  immunityId: 0,
  creator: store.curr.userName, //创建人
});

//新增养殖
const Addbreed = (addmodify: any) => {
  if (addmodify == false) {
    axios({
      method: "post",
      url: "https://localhost:44352/api/Breed/AddBreed",
      data: Addbreedbata.value,
    }).then((res) => {
      if (res.data.code == 300) {
        ElMessage.success(res.data.message);
        from1.dialogFormVisible = false;
        Getbreed();
      } else {
        // 处理其他错误码
        ElMessage.error(res.data.message);
      }
    });
  } else {
    axios({
      method: "put",
      url: "https://localhost:44352/api/Breed/UpdateBreed",
      data: {
        breedId: Addbreedbata.value.breedId,
        variety: Addbreedbata.value.variety,
        source: Addbreedbata.value.source,
        feedingDays: Addbreedbata.value.feedingDays,
        feedingBrand: Addbreedbata.value.feedingBrand,
        feedingName: Addbreedbata.value.feedingName,
        saleDate: Addbreedbata.value.saleDate,
      },
    }).then((res) => {
      if (res.data.code == 400) {
        ElMessage.success(res.data.message);
        from1.dialogFormVisible = false;
      } else {
        // 处理其他错误码
        ElMessage.error(res.data.message);
      }
    });
  }
};
//查询养殖
const Getbreed = () => {
  axios({
    method: "get",
    url: "https://localhost:44352/api/Breed/QueryBreed",
    params: {
      ProductId: route.query.productId,
    },
  }).then((res) => {
    if (res.data.code == 200) {
      Addbreedbata.value.breedId = res.data.data.breedId;
      Addbreedbata.value.variety = res.data.data.variety;
      Addbreedbata.value.source = res.data.data.source;
      Addbreedbata.value.feedingDays = res.data.data.feedingDays;
      Addbreedbata.value.feedingBrand = res.data.data.feedingBrand;
      Addbreedbata.value.feedingName = res.data.data.feedingName;
      Addbreedbata.value.saleDate = res.data.data.saleDate;
      Addbreedbata.value.farmEnterpriseId = res.data.data.farmEnterpriseId;
      Addbreedbata.value.immunityId = res.data.data.immunityId;
      from1.AddModify = true;
    } else {
      from1.AddModify = false;
    }
  });
};

//#endregion
</script>
<style >
/* 定义滚动条的整体样式 */
::-webkit-scrollbar {
  width: 5px; /* 滚动条宽度 */
}

/* 定义滚动条轨道的样式 */
::-webkit-scrollbar-track {
  background-color: #f1f1f1; /* 轨道背景颜色 */
}

/* 定义滚动条滑块的样式 */
::-webkit-scrollbar-thumb {
  background-color: #888; /* 滑块背景颜色 */
  border-radius: 4px; /* 滑块圆角 */
}

/* 当鼠标悬停在滑块上时的样式 */
::-webkit-scrollbar-thumb:hover {
  background-color: #555; /* 悬停时滑块背景颜色 */
}
</style>